
(function($)
{
    $.Wiloke =  $.Wiloke || {};
    $(document).ready(function()
    {
        /* Choose Icon */
        var codeFa, showIcon, insertCode,  _self = "";;

        $(".available-panel.thickbox").live("mouseenter mouseleave", function(event)
        {
            if (event.type == "mouseenter")
            {   
                _self = $(this);

                $("#fa-table-list i.fa").live("click", function(){
                    codeFa = $(this).attr("class");
                    codeFa = codeFa + " mdicon";
                    
                    _self.find("i.fa").attr("class", codeFa);
                    _self.next().val(codeFa);
                    tb_remove();
                })
            }else{

            }
        });

        $(document).on("click", ".wo-addmore", function(event)
        {
            event.preventDefault();
            var clone = "", needFindChild = false, currentId;

            if ($(this).parents(".wo-wrapclone").prev().hasClass("clone-me"))
            {
                needFindChild = true;
            }

            if (needFindChild == true)
            {
                clone = $(this).parents(".wo-wrapclone").prev().clone();
            }else{
                clone = $(this).parents(".wo-wrapclone").prev().find(".md-person.clone-me:first-child").clone();
            }


            clone.find(".tab-content").text("");

            clone.find(".service_name, .service_description").val("");

            clone.find("input.reset, textarea.reset").val("");
            clone.find(".is_icon").val("fa fa-refresh");
            clone.find(".is_icon, .mdicon").attr("class", "fa fa-refresh");
            clone.find(".logo_placeholder").attr("src", WO_QVA.logo);
            clone.find(".image_placeholder").attr("src", WO_QVA.placeholder);
            clone.find(".lux-gallery.logo img").attr("src", WO_QVA.logo);

            if (!needFindChild)
            {
                clone.removeClass("clone-me");
            }

            currentId = clone.find(".wo-current-id").val();

            var numSocial = clone.find(".wo_toggle");



            if (numSocial.length > 0)
            {
                for (var i=1; i<numSocial.length; i++ )
                {
                    clone.find(".wo_toggle:nth-child("+i+")").remove();
                }
            }



            if (typeof (currentId) != 'null' && typeof currentId != 'undefined')
            {
                var upCurrentId = parseInt(currentId) + 1;

                clone.find(".social_link").val("#");
                clone.find(".social_link").attr("name", "ourteam[social_icon]["+upCurrentId+"][]");
                clone.find(".social_name").attr("name", "ourteam[social_name]["+upCurrentId+"][]");
                clone.find(".social_icon").attr("name", "ourteam[social_icon]["+upCurrentId+"][]");
                clone.find(".bo-picture-ourteam, .ourteam_picture").attr("src", WO_QVA.placeholder);
            }



            if (needFindChild == true)
            {
                $(this).parents(".wo-wrapclone").prev().after(clone);
            }else{
                $(this).parents(".wo-wrapclone").prev().find("div.md-person:last-child").after(clone);
            }
            clone="";
        })

        var formSocial = '<div class="wrap-social">\
                        <h4 class="toggle-title">Social networks  <i class="fa fa-times right wo-delete-social"></i></h4>\
                        <div class="toggle-content">\
                            <div class="form-group">\
                                <label class="form-label">Name</label>\
                                <div class="controls">\
                                    <input type="text" value="" name="ourteam[social_name][]" class="form-control">\
                                </div>\
                            </div>\
                            <div class="form-group icon-wrap">\
                                <label class="form-label">Social Icon</label>\
                                    <a href="#TB_inline?width=600&height=550&inlineId=table-fa" class="available-panel thickbox">Change icon\
                                        <i class="fa fa-home"></i>\
                                    </a>\
                                    <input type="hidden" name="ourteam[social_icon][]" class="social_icon" value="">\
                            </div>\
                            <div class="form-group">\
                                <label class="form-label">Link</label>\
                                <div class="controls">\
                                    <input type="text" value="#" name="ourteam[link][]" class="form-control">\
                                </div>\
                            </div>\
                        </div>\
                        </div>';


        $(document).on("click", ".delele-this", function(event)
        {
            event.preventDefault();
            var _parents = $(this).parents(".wrap-delete");
            if ( !( (_parents.next()).hasClass("wrap-delete") ) &&  !( (_parents.prev()).hasClass("wrap-delete") ) )
            {
                alert("Opp! You have only one item")
            }else{
                
                _parents.remove();
            }
        })


        // add social 
        $(".wo-addsocial").on("click", function(event)
        {
            event.preventDefault();
            var _self = $(this);
            _self.parents(".add-social").before(formSocial);
        })


        $(".bo-delete").live("click", function()
        {

            if ( ($(this).parents(".wrap-all").find(".wrap-delete")).length > 1 )
            {
                console.log("a");

                    if ($(this).parents(".wrap-delete").hasClass("clone-me"))
                    {
                        if (!($(this).hasClass("fix-delete")))
                        {
                            $(this).parent().next().addClass("clone-me");
                            $(this).parent().fadeOut('slow', function()
                                {
                                        $(this).remove();
                                }
                            );
                        }else{
                            $(this).parents(".wrap-delete").fadeOut('slow', function(){
                                $(this).remove();
                            })
                        }
                    }else{
                        $(this).parents(".wrap-delete").fadeOut('slow', function()
                            {
                                $(this).remove();
                            }
                        );
                    }
                }
        })

        $(".formtype").change(function(){
            if ($("#external").prop('checked'))
            {
                $(".wrap-embedshortcode").show();
            }else{
                $(".wrap-embedshortcode").hide();
            }
        }).trigger("change");

        $(".headertype").change(function()
        {
            if ($("#imageslideshow").prop('checked'))
            {
                $(".zone-of-staticimg, .zone-of-youtube").hide();
                $(".zone-of-slideshow").show();
            }else if($("#youtube").prop('checked')){
                $(".zone-of-staticimg, .zone-of-slideshow").hide();
                $(".zone-of-youtube").show();
            }else{
                $(".zone-of-slideshow, .zone-of-youtube").hide();
                $(".zone-of-staticimg").show();
            }
        }).trigger("change");     

        $(".toggle-wrap").live("click", function()
        {
            $(this).next().toggle("fast");
        })

        $('.toggle-title').live("click", function() {

            $(this).toggleClass("highlight");
            $(this).next().slideToggle(500);

        });
        
        $.Wiloke.wo_media_upload(".upload-image, .multiple_upload");

        $(".photo").click(function()
        {   
            var current = $(this);
            var send_attachment_bkp = wp.media.editor.send.attachment;

            wp.media.editor.send.attachment = function(props, attachment) {
                // var image_size =  props.size;
                var image_url = attachment.url;
                var thumbnail = attachment.sizes.thumbnail.url;
                if (!current.hasClass("blog-img"))
                {
                    current.next().val(image_url);
                }else{
                    current.next().val(attachment.id);
                }
                current.children().attr("src", thumbnail);
                wp.media.editor.send.attachment = send_attachment_bkp;
            }

            wp.media.editor.open();
            return false;
        })
        $.Wiloke.wo_remove_image(".md-remove"); 

        $(".wo-delete-social").live( "click", function(event)
        {
            event.preventDefault();
            // var numSocial = $(this).parents(".wrap-social");
           
           ($(this).parents(".wrap-social")).remove();
               
            if ($(this).hasClass("not-remove"))
            {
                $(".form-group.add-toggle").before(formSocial);
            }
        })

        $(".choosidebar").click( function(){
            var sidebar="";
                $(".choosidebar").removeClass("sidebar-active");
                $(this).addClass("sidebar-active"); 
                sidebar = $(this).data("sidebar");
                $("input.sidebar-value").attr("value",sidebar);
            return false;
        })

    })






    /*
     * Media Upload
     * Prerefence http://mikejolley.com/2012/12/using-the-new-wordpress-3-5-media-uploader-in-plugins/
     * Many Thanks mikejolley
     */

    $.Wiloke.wo_media_upload = function(uploadType)
    {

        var _self, file_frame, mdInsertTo= "", mdGallery= "", isMultile=true, liveInsertMe=false;
        // console.log(uploadType);
        /* Multiple or single Upload */


        $(uploadType).live("click", function(event)
        {
            event.preventDefault();
            _self = $(this);
            if ( !$(this).hasClass("multiple_upload") )
            {
                isMultile = false;
            }else{
                isMultile = true;
            }

            if ($(this).hasClass("live_insert_me"))
            {
                liveInsertMe = true;
            }

            // console.log(isMultile);
            /* get id of input that will insert image src or images id to */
            mdInsertTo = $(this).prev();

            /* get id gallery */
            mdGallery = $(this).parent().next();

            if (!mdGallery.hasClass("lux-gallery"))
            {
                mdGallery = $(this).find(".lux-gallery");
            }else if ( $(this).next().hasClass("show-image") )
            {
                mdGallery = $(this).next();
            }

            /* If the media frame already exists, reopen it. */
            // if ( file_frame )
            // {
            // 	file_frame.open();
            // 	return;
            // }

            /* Create the media frame */
            file_frame = wp.media.frames.file_frame = wp.media(
                {
                    title: jQuery( this ).data( 'uploader_title' ),
                    button: {
                        text: jQuery(this).data('uploader_button_title'),
                    },
                    multiple: isMultile,

                })

            /* When an image or many images is selected, run a callback */
            file_frame.on("select", function()
            {
                var selection = file_frame.state().get('selection');
                switch (isMultile)
                {
                    case true:

                        var ids = [], urls = [], idsurls = [];

                        selection.map(function(attachment)
                        {
                            attachment 	= attachment.toJSON();
                            ids.push(attachment.id);

                            if (typeof attachment.sizes.thumbnail !== 'undefined')
                            {
                                urls.push(attachment.sizes.thumbnail.url);
                            }else{
                                urls.push(attachment.url);
                            }
                        });

                        var oldids = $.map($(mdInsertTo).val().split(","), function(value)
                        {
                            if (value != "")
                                return parseInt(value, 10);
                        });

                        for (var j = 0; j < ids.length; j++)
                        {
                            oldids.push(ids[j]);
                            var img = '<li class="attachment img-item width-300" data-id="'+ids[j]+'"><image  src="' + urls[j] + '" /><a href="#" class="md-remove"><i class="fa fa-times"></i></a></li>';

                            $(mdGallery).append(img);
                        }

                        $(mdInsertTo).val(oldids);
                        break;

                    case false:

                        var logoUrl, origionUrl;
                        selection.map(function(attachment)
                        {
                            attachment = attachment.toJSON();

                            if (typeof attachment.sizes.thumbnail !== 'undefined')
                            {
                                logoUrl = attachment.sizes.thumbnail.url;
                            }else{
                                logoUrl = attachment.url;
                            }

                            origionUrl = attachment.url;
                        });
                        if (liveInsertMe == false)
                        {
                            $(mdInsertTo).val(origionUrl);

                            var img = '<img class="img-item" src="'+logoUrl+'">';
                            $(mdGallery).children().remove();
                            $(mdGallery).append(img);
                        }else{
                            _self.attr("src", logoUrl);
                            _self.next().val(origionUrl);
                        }
                        break;
                }
            })

            /* Finally,  open the modal */
            file_frame.open();

        })

    }

    $.Wiloke.another_media_upload = function(uploadType)
    {
        
        var file_frame, mdInsertTo= "", mdGallery= "", isMultile=true;
            // console.log(uploadType);
            /* Multiple or single Upload */
            

            $(document).on("click", uploadType, function(event)
            {
                event.preventDefault();

                if ( !$(this).hasClass("multiple_upload") )
                {
                    isMultile = false;
                }else{
                    isMultile = true;
                }
                // console.log(isMultile);
                /* get id of input that will insert image src or images id to */
                mdInsertTo = $(this).prev();

                /* get id gallery */
                mdGallery = $(this).next();

                /* If the media frame already exists, reopen it. */
                // if ( file_frame )
                // {
                //  file_frame.open();
                //  return;
                // }

                /* Create the media frame */
                file_frame = wp.media.frames.file_frame = wp.media(
                {
                    title: jQuery( this ).data( 'uploader_title' ),
                    button: {
                        text: jQuery(this).data('uploader_button_title'),
                    },
                    multiple: isMultile,

                })

                /* When an image or many images is selected, run a callback */
                file_frame.on("select", function()
                {
                    var selection = file_frame.state().get('selection');
                    switch (isMultile)
                    {
                        case true:
                            console.log("a");
                                var ids = [], urls = [], idsurls = [];

                                selection.map(function(attachment)
                                {
                                    attachment  = attachment.toJSON();
                                    ids.push(attachment.id);
                                    urls.push(attachment.sizes.thumbnail.url);
                                });

                                var oldids = $.map($(mdInsertTo).val().split(","), function(value)
                                            {
                                                if (value != "")
                                                    return parseInt(value, 10);
                                            });

                                    for (var j = 0; j < ids.length; j++)
                                    {
                                        oldids.push(ids[j]);
                                        var img = '<li class="img-item width-300" data-id="'+ids[j]+'"><img  src="' + urls[j] + '" /><a href="#" class="md-remove"><i class="fa fa-times"></i></a></li>';

                                        $(mdGallery).append(img);
                                    }

                                    $(mdInsertTo).val(oldids);
                        break;

                        case false:
                                var logoUrl;
                                selection.map(function(attachment)
                                {
                                    attachment = attachment.toJSON();
                                    logoUrl = attachment.url;
                                });
                                $(mdInsertTo).val(logoUrl);

                                var img = '<li class="img-item width-300"><img  src="'+logoUrl+'"></li>';
                                $(mdGallery).children().remove();
                                $(mdGallery).append(img);
                        break;
                    }
                })

                /* Finally,  open the modal */
                file_frame.open();

            })
        
    }

    /* Remove Image */
    $.Wiloke.wo_remove_image = function(className)
    {
        $(document).on("click", className, function(event)
        {
            // console.log("a");
            event.preventDefault();

            var getVal = $(this).parent().parent().prev().find(".box-image-id");
 
            var index = $(this).parent().data("id"),
            oldids = $.map(getVal.val().split(','), function(value)
                     {
                        if (value != "")
                            return parseInt(value, 10);
                     });

            if (oldids.length > 1)
            {
              oldids = $.Wiloke.wo_removeId(oldids, index);
              getVal.val(oldids.join(","));
            }else{
              getVal.val("");
            }
            
           if ($(this).parent().length > 0)
           {
               $(this).parent().fadeOut('slow', function() 
               {
                  $(this).remove();
               });
            }
        });
    };

    $.Wiloke.wo_removeId = function(arr, id)
    {
        for(var i=0; i<arr.length; i++)
        {
           if (arr[i] == id)
           {
              arr.splice(i, 1);
           }
        }

        return arr;
    }
})(jQuery)
